package com.zfzs.post.modules.flow.service.impl;

import com.zfzs.post.modules.agent.domain.AgentVerified;
import com.zfzs.post.modules.agent.service.AgentMoneyService;
import com.zfzs.post.modules.agent.service.AgentService;
import com.zfzs.post.modules.agent.service.AgentVerifiedService;
import com.zfzs.post.modules.agent.service.PolicyDividedService;
import com.zfzs.post.modules.common.service.AgentContactService;
import com.zfzs.post.modules.flow.domain.FlowActiv;
import com.zfzs.post.modules.flow.domain.OtherIncome;
import com.zfzs.post.modules.flow.service.FlowActivService;
import com.zfzs.post.modules.flow.service.FlowWebService;
import com.zfzs.post.modules.flow.service.OtherIncomeService;
import com.zfzs.post.modules.merchant.domain.Merchant;
import com.zfzs.post.modules.merchant.service.MerchantService;
import com.zfzs.post.modules.post.domain.TerminalInfo;
import com.zfzs.post.modules.post.domain.TerminalType;
import com.zfzs.post.modules.post.service.TerminalInfoService;
import com.zfzs.post.modules.post.service.TerminalTypeService;
import com.zfzs.post.modules.post.service.mybatis.ITerminalInfoService;
import com.zfzs.post.utils.MathUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wq
 * @date 2019/11/29 10:26
 * @description
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class FlowWebServiceImpl implements FlowWebService {

    @Autowired
    private ITerminalInfoService iTerminalInfoService;

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private PolicyDividedService policyDividedService;

    @Autowired
    private AgentMoneyService agentMoneyService;

    @Autowired
    private FlowActivService flowActivService;

    @Autowired
    private AgentContactService agentContactService;

    @Autowired
    private OtherIncomeService otherIncomeService;

    @Autowired
    private TerminalTypeService terminalTypeService;

    @Autowired
    private AgentVerifiedService agentVerifiedService;

    @Autowired
    private AgentService agentService;

    @Autowired
    private TerminalInfoService terminalInfoService;

    @Override
    public void activateTerminal(Long channelId) {

        List<TerminalInfo> infoList = iTerminalInfoService.findActivatingTerminal(channelId);

        infoList = filterTerminal(infoList, channelId);

        for (TerminalInfo t : infoList) {

            String sn = t.getSn();
            Merchant merchant = merchantService.findBySn(sn);

            if (merchant == null) {
                continue;
            }

            List<FlowActiv> fa = flowActivService.findBySn(sn);
            if(fa!=null && !fa.isEmpty()){
                continue;
            }
            Long agentId = merchant.getAgentId();
            Long terminalTypeId = merchant.getTerminalTypeId();

            String names = "激活返现";

            BigDecimal amount = policyDividedService.getPolicyAmount(agentId, terminalTypeId, channelId, names);

            addFLowActiv(channelId, sn, agentId, agentId, amount);

            List<Long> parentIdList = agentContactService.findAllParentIdList(agentId, channelId);


            for (int i = 0; i < parentIdList.size(); i++) {
                if (i < parentIdList.size() - 1) {
                    Long childId = parentIdList.get(i);
                    Long activAgentId = parentIdList.get(i + 1);
                    BigDecimal childAmount = policyDividedService.getPolicyAmount(childId, terminalTypeId, channelId, names);

                    BigDecimal activAmount = policyDividedService.getPolicyAmount(activAgentId, terminalTypeId, channelId, names);

                    BigDecimal realAmount = activAmount.subtract(childAmount);

                    addFLowActiv(channelId, sn, agentId, activAgentId, realAmount);
                }
            }
            TerminalInfo terminalInfo = terminalInfoService.findBySN(sn);
            terminalInfo.setIsActivation(1L);
            terminalInfo.setActivationDate(Timestamp.valueOf(LocalDateTime.now()));
            terminalInfoService.update(terminalInfo);
        }
    }

    @Override
    public void vipBackAmount(String sn, String names) {
        Merchant merchant = merchantService.findBySn(sn);

        if (merchant != null) {

            Long agentId = merchant.getAgentId();

            Long channelId = merchant.getChannelId();

            Long terminalTypeId = merchant.getTerminalTypeId();

            TerminalType terminalType = terminalTypeService.findById(terminalTypeId);

           OtherIncome oi= otherIncomeService.findOneBySnAndTitle(agentId,sn,"会员充值");

           if(oi!=null){
               return;
           }
            BigDecimal amount = policyDividedService.getPolicyAmount(agentId,terminalTypeId,channelId, names);
            AgentVerified agent = agentVerifiedService.findByAgentId(agentId);
            if (amount.compareTo(new BigDecimal("0")) == 1) {

                OtherIncome income = new OtherIncome();

                income.setAgentId(agentId);
                income.setAmount(MathUtils.formatToNumber(amount));
                income.setChannelId(channelId);
                String title = names.replace("返现", "");
                income.setTitle("会员充值返现-" + title);
                income.setIcon("https://mpos-img.oss-cn-beijing.aliyuncs.com/icon/huiyuan.png");
                List<String> detailList = new ArrayList<>();
                detailList.add("设备型号:" + terminalType.getTerminalName() + terminalType.getModel());
                detailList.add("设备编号:" + sn);
                detailList.add("所属商户:" + merchant.getMerchantName());
                detailList.add("商户归属:" + agent.getCardName() + "(自己)");
                income.setDetailList(detailList);
                otherIncomeService.save(income);
                agentMoneyService.addAgentMoney(agentId,amount);

            }

            List<Long> parentIdList = agentContactService.findAllParentIdList(agentId, channelId);

            for (int i = 0; i < parentIdList.size(); i++) {

                if (i < parentIdList.size() - 1) {
                    Long childId = parentIdList.get(i);
                    Long activAgentId = parentIdList.get(i + 1);
                    BigDecimal childAmount = policyDividedService.getPolicyAmount(childId, terminalTypeId, channelId, names);

                    BigDecimal activAmount = policyDividedService.getPolicyAmount(activAgentId, terminalTypeId, channelId, names);

                    BigDecimal realAmount = activAmount.subtract(childAmount);

                    if (realAmount.compareTo(new BigDecimal("0")) == 1) {

                        OtherIncome income = new OtherIncome();

                        income.setAgentId(activAgentId);
                        income.setAmount(MathUtils.formatToNumber(realAmount));
                        income.setChannelId(channelId);
                        String title = names.replace("返现", "");
                        income.setTitle("会员充值返现-" + title);

                        income.setIcon("https://mpos-img.oss-cn-beijing.aliyuncs.com/icon/huiyuan.png");
                        List<String> detailList = new ArrayList<>();

                        detailList.add("设备型号:" + terminalType.getTerminalName() + terminalType.getModel());

                        detailList.add("设备编号:" + sn);

                        detailList.add("所属商户:" + merchant.getMerchantName());

                        Boolean directly = agentService.isDirectly(agentId, activAgentId);

                        detailList.add("商户归属:" + agent.getCardName() + (directly? "(直营)":"(合伙人)"));

                        income.setDetailList(detailList);

                        otherIncomeService.save(income);

                        agentMoneyService.addAgentMoney(activAgentId,realAmount);

                    }

                }
            }
        }

    }

    @Override
    public void depositAmount(String sn) {
        Merchant merchant = merchantService.findBySn(sn);

        if (merchant != null) {

            String names="押金返现";

            Long agentId = merchant.getAgentId();

            Long channelId = merchant.getChannelId();

            Long terminalTypeId = merchant.getTerminalTypeId();

            OtherIncome oi= otherIncomeService.findOneBySnAndTitle(agentId,sn,names);

            if(oi!=null){
                return;
            }

            TerminalType terminalType = terminalTypeService.findById(terminalTypeId);

            BigDecimal amount = policyDividedService.getPolicyAmount(agentId, terminalTypeId, channelId,names);
            AgentVerified agent = agentVerifiedService.findByAgentId(agentId);
            if (amount.compareTo(new BigDecimal("0")) == 1) {

                OtherIncome income = new OtherIncome();

                income.setAgentId(agentId);
                income.setAmount(MathUtils.formatToNumber(amount));
                income.setChannelId(channelId);
                income.setTitle("押金返现-交易达标");
                income.setIcon("https://mpos-img.oss-cn-beijing.aliyuncs.com/icon/yajin.png");
                List<String> detailList = new ArrayList<>();
                detailList.add("设备型号:" + terminalType.getTerminalName() + terminalType.getModel());
                detailList.add("设备编号:" + sn);
                detailList.add("所属商户:" + merchant.getMerchantName());
                detailList.add("商户归属:" + agent.getCardName() + "(自己)");
                income.setDetailList(detailList);
                otherIncomeService.save(income);
                agentMoneyService.addAgentMoney(agentId,amount);

            }

            List<Long> parentIdList = agentContactService.findAllParentIdList(agentId, channelId);

            for (int i = 0; i < parentIdList.size(); i++) {

                if (i < parentIdList.size() - 1) {
                    Long childId = parentIdList.get(i);
                    Long activAgentId = parentIdList.get(i + 1);
                    BigDecimal childAmount = policyDividedService.getPolicyAmount(childId, terminalTypeId, channelId, names);

                    BigDecimal activAmount = policyDividedService.getPolicyAmount(activAgentId, terminalTypeId, channelId, names);

                    BigDecimal realAmount = activAmount.subtract(childAmount);

                    if (realAmount.compareTo(new BigDecimal("0")) == 1) {

                        OtherIncome income = new OtherIncome();

                        income.setAgentId(activAgentId);
                        income.setAmount(MathUtils.formatToNumber(realAmount));
                        income.setChannelId(channelId);

                        income.setTitle("押金返现-交易达标");

                        income.setIcon("https://mpos-img.oss-cn-beijing.aliyuncs.com/icon/yajin.png");
                        List<String> detailList = new ArrayList<>();

                        detailList.add("设备型号:" + terminalType.getTerminalName() + terminalType.getModel());

                        detailList.add("设备编号:" + sn);

                        detailList.add("所属商户:" + merchant.getMerchantName());

                        Boolean directly = agentService.isDirectly(agentId, activAgentId);

                        detailList.add("商户归属:" + agent.getCardName() + (directly? "(直营)":"(合伙人)"));

                        income.setDetailList(detailList);

                        otherIncomeService.save(income);

                        agentMoneyService.addAgentMoney(activAgentId,realAmount);

                    }

                }
            }
        }



    }

    /**
     * 添加激活返现的流水
     * @param channelId
     * @param sn
     * @param activAgentId
     * @param reapAgentId
     * @param realAmount
     */
    private void addFLowActiv(Long channelId, String sn, Long activAgentId, Long reapAgentId, BigDecimal realAmount) {

        if (realAmount.compareTo(new BigDecimal("0")) == 1) {
            //添加记录
            FlowActiv flowActiv = new FlowActiv();
            flowActiv.setActivAgent(activAgentId);
            flowActiv.setAgentId(reapAgentId);
            flowActiv.setAmount(realAmount);
            flowActiv.setSn(sn);
            flowActiv.setCreateTime(new Date());
            flowActiv.setChannelId(channelId);
            flowActivService.create(flowActiv);

            agentMoneyService.addAgentMoney(activAgentId, realAmount);

        }
    }

    /**
     * 用于筛选机器列表
     *
     * @param infoList
     * @param channelId
     * @return
     */
    private List<TerminalInfo> filterTerminal(List<TerminalInfo> infoList, Long channelId) {

        return infoList;
    }
}
